#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author :

import os
from typing import Text
import yaml

# linux已经调试，没有问题
from common.path_setting import ensure_path_sep
import jsonpath
from common.get_logger import GetLogger
from config import config

log = GetLogger.get_logger()


class YamlUtil:

    # 读取提取文件,通过key读取extract.yaml文件
    @staticmethod
    def read_extract_yaml(key):
        with open(ensure_path_sep("\\extract.yaml"), mode="r", encoding="utf-8") as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data[key]

    @staticmethod
    def write_extract_yaml(data):
        with open(ensure_path_sep("\\extract.yaml"), mode="r", encoding="utf-8") as file:
            old_result = yaml.safe_load(file)
            if old_result is not None:
                for key, value in dict(data).items():
                    if key in old_result:
                        log.info(f"键[{key}]已存在,他的值从[{old_result[key]}]替换为[{value}]")
                        old_result[key] = value
                        with open(ensure_path_sep("\\extract.yaml"), mode="w", encoding="utf-8") as replace_file:
                            data = yaml.dump(data=old_result, stream=replace_file, allow_unicode=True)
                    else:
                        with open(ensure_path_sep("\\extract.yaml"), mode="a", encoding="utf-8") as add_file:
                            data = yaml.dump(data=data, stream=add_file, allow_unicode=True)
            else:
                with open(ensure_path_sep("\\extract.yaml"), mode="a", encoding="utf-8") as add_file:
                    data = yaml.dump(data=data, stream=add_file, allow_unicode=True)
            return data

    # 读取测试数据
    @staticmethod
    def read_testdata_yaml(key):
        with open(ensure_path_sep("\\config\\test_data.yaml"), mode="r", encoding="utf-8") as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data[config.env][key]
